import React, { useState, useEffect, useRef } from 'react';
import { DownOutlined, SettingTwoTone, EyeTwoTone, PlusOutlined } from '@ant-design/icons';
import {
    Button, Row, Col, DatePicker, Form, Input,
    Select, Dropdown, Space, Divider,
    Radio, Table, Tag, Modal, Drawer
} from 'antd';
import { getAllUserListApi, addUserApi } from '../../api/user';

export default function User() {
    const FormRef = useRef()
    const [initialValues, setInitialValues] = useState({})
    const [open, setOpen] = useState(false);//新增抽屉默认隐藏
    const [user, setUser] = useState({})
    const userinfo = JSON.parse(localStorage.user)
    // console.log(userinfo);
    const [isModalOpen, setIsModalOpen] = useState(false); // 查看弹出框内部
    const [list, setList] = useState([])
    const [selectionType, setSelectionType] = useState('checkbox');
    // 查看
    // const [isModalOpen, setIsModalOpen] = useState(false);
    const showModal = (scope) => {
        console.log('scope', scope);
        setUser(scope)
        // console.log('user',user);
        setIsModalOpen(true);
    };
    const handleOk = () => {
        setIsModalOpen(false);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const columns = [
        {
            title: '用户名',
            dataIndex: 'username',
            sorter: (a, b) => a.age - b.age,
        },
        {
            title: '性别',
            dataIndex: 'ssex',
            filters: [
                {
                    text: '男',
                    value: '1',
                },
                {
                    text: '女',
                    value: '0',
                },
                {
                    text: '保密',
                    value: '2',
                },
            ],
            onFilter: (value, record) => record.address.indexOf(value) === 0,
        },
        {
            title: '邮箱',
            dataIndex: 'email',
        },
        {
            title: '部门',
            dataIndex: 'deptName',
        },
        {
            title: '电话',
            dataIndex: 'mobile',
        },
        {
            title: '状态',
            dataIndex: 'status',
            filters: [
                {
                    text: '有效',
                    value: '1',
                },
                {
                    text: '锁定',
                    value: '0',
                },
            ],
            render: (status) => {
                if (status == '有效') {
                    return <Tag color="cyan">{status}</Tag>
                } else if (status == '锁定') {
                    return <Tag color="red">{status}</Tag>
                }
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            sorter: (a, b) => a.createTime - b.createTime,
            // sorter: true,
        },
        {
            title: '操作',
            dataIndex: 'address',
            render: (_, scope) => (
                <Space size="middle">
                    <SettingTwoTone twoToneColor="#5599FF" onClick={() => showDrawer(scope)} />
                    <EyeTwoTone twoToneColor="#00CC00" onClick={() => showModal(scope)} />
                </Space>
            ),
        },
    ];

    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        },
        getCheckboxProps: (record) => ({
            disabled: record.name === 'Disabled User',
            // Column configuration not to be checked
            name: record.name,
        }),
    };
    const handleButtonClick = (e) => {
        message.info('Click on left button.');
        console.log('click left button', e);
    };
    const handleMenuClick = (e) => {
        message.info('Click on menu item.');
        console.log('click', e);
    };

    const items = [
        {
            label: '密码重置',
            key: '1',
        },
        {
            label: '导出Excel',
            key: '2',
        },
    ];
    const menuProps = {
        items,
        onClick: handleMenuClick,
    };
    const { Option } = Select;
    const { RangePicker } = DatePicker;
    const layout = {
        labelCol: {
            span: 8,
        },
        wrapperCol: {
            span: 30,
        },
    };
    const tailLayout = {
        wrapperCol: {
            offset: 8,
            span: 16,
        },
    };

    const [form] = Form.useForm();
    const onGenderChange = (value) => {
        console.log(value);
    };
    const onFinish = (values) => {
        console.log(values);
    };
    const onReset = () => {
        form.resetFields();
    };

    const rangeConfig = {
        rules: [
            {
                type: 'array',
                required: true,
                message: '请选择时间!',
            },
        ],
    };

    // 点击新增弹出抽屉
    const showDrawer = (record) => {
        if (record.userId) {
            // 修改
            console.log('record', record);
            setInitialValues({
                username:record.username,
                email:record.email,
                mobile:record.mobile,
                roleId:record.roleName,
                deptId:record.deptName,
                status:record.status,
                ssex:record.ssex,
            })
        } else {
            // 新增
            console.log('新增');
            setInitialValues({
                password: '1234qwer'
            })
        }
        setOpen(true);
    };

    // 点击关闭抽屉
    const onClose = (values) => {
        setOpen(false);
        console.log('============', values);
        const { username, password, roleId, status, ssex, email, mobile, deptId } = values
        if (!password) {
            // 修改接口
            console.log('修改接口');
        }else{
            // 新增接口
            console.log('新增接口');
        }
        // console.log(username, password, roleId, status, ssex, email, mobile, deptId);
        // addUserApi(username, password, roleId, status, ssex, email, mobile, deptId).then(res => {
        //     console.log('------------res', res);
        // })
    };

    // 调用接口
    useEffect(() => {
        getAllUserListApi().then(res => {
            const data = res.rows
            data.forEach(item => {
                if (item.ssex == '1') {
                    item.ssex = '男'
                } else if (item.ssex == '0') {
                    item.ssex = '女'
                } else if (item.ssex == '2') {
                    item.ssex = '保密'
                }
                if (item.status == '0') {
                    item.status = '锁定'
                } else if (item.status == '1') {
                    item.status = '有效'
                }
            })
            setList(data)
        })
    }, [])

    const options = [
        { label: '管理员', value: "1" },
        { label: '注册用户', value: '2' },
        { label: '普通用户', value: '3' },
        { label: '商户', value: '4' },
    ];
    const handleChange = (value) => {
        console.log(`selected ${value}`);
    };

    return (
        <div>
            <Form {...layout} form={form} name="control-hooks" onFinish={onFinish} style={{ display: 'flex' }}>
                <Form.Item
                    name="用户名"
                    label="用户名："
                    rules={[
                        {
                            required: true,
                        },
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="部门"
                    label="部门"
                    rules={[
                        {
                            required: true,
                        },
                    ]}
                >
                    <Select
                        placeholder="请选择所在部门"
                        onChange={onGenderChange}
                        allowClear
                    >
                        <Option value="1">开发部</Option>
                        <Option value="4">市场部</Option>
                        <Option value="5">人事部</Option>
                        <Option value="6">测试部</Option>
                    </Select>
                </Form.Item>
                <Form.Item name="range-picker" label="创建时间" {...rangeConfig}>
                    <RangePicker />
                </Form.Item>
                {/* <Form.Item
                        noStyle
                        shouldUpdate={(prevValues, currentValues) => prevValues.gender !== currentValues.gender}
                    >
                        {({ getFieldValue }) =>
                            getFieldValue('gender') === 'other' ? (
                                <Form.Item
                                    name="customizeGender"
                                    label="Customize Gender"
                                    rules={[
                                        {
                                            required: false,
                                        },
                                    ]}
                                >
                                    <Input />
                                </Form.Item>
                            ) : null
                        }
                    </Form.Item> */}
                <Button type="primary" htmlType="submit">
                    查询
                </Button>
                <Button htmlType="button" onClick={onReset}>
                    重置
                </Button>
                {/* <Form.Item {...tailLayout} style={{ display: 'flex', alignItems: 'center' }}>
                        <Button type="link" htmlType="button" >
                            Fill form
                        </Button>
                    </Form.Item> */}
            </Form>
            <Button onClick={showDrawer} icon={<PlusOutlined />}>新增</Button>
            <Button>删除</Button>
            <Dropdown menu={menuProps}>
                <Button>
                    <Space>
                        更多操作
                        <DownOutlined />
                    </Space>
                </Button>
            </Dropdown>
            <div>
                <Divider />
                <Table
                    rowSelection={{
                        type: selectionType,
                        ...rowSelection,
                    }}
                    columns={columns}
                    dataSource={list}
                    rowKey={((record) => record.userId)}
                />
            </div>

            {/* 查看===>模态框 */}

            <Modal title="用户信息" width={750} okText='确定' cancelText='取消'
                open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <div className="user_modal_box">
                    <img src={`http://xawn.f3322.net:8002/distremote/static/avatar/${user.avatar}`}
                        alt="头像"
                        style={{ width: '115px', height: '115px', borderRadius: '5px' }} />
                    <div className="user_modal_right_left">
                        <p>账户：{user.username}</p>
                        <p>角色：{user.roleName}</p>
                        <p>性别：{user.ssex}</p>
                        <p>电话：{user.mobile}</p>
                        <p>邮箱：{user.email}</p>
                    </div>
                    <div className="user_modal_right_right">
                        <p>部门：{user.deptName}</p>
                        <p>状态：<Tag color="cyan">{user.status}</Tag></p>
                        <p>创建时间：{user.createTime}</p>
                        <p>最近登录：{user.lastLoginTime}</p>
                        <p>描述：{user.description}</p>
                    </div>
                </div>
            </Modal>


            {/* 新增模态框 */}
            <Drawer
                title="新增用户"
                width={700}
                onClose={onClose}
                open={open}
                closable={false}
                bodyStyle={{
                    paddingBottom: 80,
                }}
            >
                <Form layout="vertical" hideRequiredMark onFinish={onClose} ref={FormRef} initialValues={initialValues}>
                    {/* <Row gutter={16}> */}
                    <Col span={16}>
                        <Form.Item
                            name="username"
                            label="用户名："
                            rules={[
                                {
                                    required: true,
                                    message: '请输入用户名',
                                },
                            ]}
                        >
                            <Input placeholder="请输入用户名" />
                        </Form.Item>
                    </Col>
                    <Col span={16}>
                        <Form.Item
                            name="password"
                            label="密码："
                            rules={[
                                {
                                    required: false,
                                    message: '请输入密码',
                                },
                            ]}
                        >
                            <Input type='password' />
                        </Form.Item>
                    </Col>
                    <Col span={16}>
                        <Form.Item
                            name="email"
                            label="邮箱："
                            rules={[
                                {
                                    required: true,
                                    message: '请输入您的邮箱账号',
                                },
                            ]}
                        >
                            <Input placeholder="请输入邮箱账号" />
                        </Form.Item>
                    </Col>
                    <Col span={16}>
                        <Form.Item
                            name="mobile"
                            label="手机："
                            rules={[
                                {
                                    required: true,
                                    message: '请输入您的手机号码',
                                },
                            ]}
                        >
                            <Input placeholder="请输入手机号" />
                        </Form.Item>
                    </Col>
                    <Col span={16}>
                        <Form.Item
                            name="roleId"
                            label="角色："
                            rules={[
                                {
                                    required: true,
                                    message: '请选择您的角色',
                                },
                            ]}
                        >
                            <Select
                                mode="multiple"
                                allowClear
                                style={{
                                    width: '100%',
                                }}
                                placeholder="请选择您的角色"
                                onChange={handleChange}
                                options={options}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={16}>
                        <Form.Item
                            name="deptId"
                            label="部门："
                            rules={[
                                {
                                    required: true,
                                    message: '请选择您所属部门',
                                },
                            ]}
                        >
                            <Select placeholder="请选择您所属部门">
                                <Option value="1">开发部</Option>
                                <Option value="4">市场部</Option>
                                <Option value="5">人事部</Option>
                                <Option value="6">测试部</Option>
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col span={16}>
                        <Form.Item name="status" label="状态：">
                            <Radio.Group>
                                <Radio value="0">锁定</Radio>
                                <Radio value="1">有效</Radio>
                            </Radio.Group>
                        </Form.Item>
                    </Col>
                    <Col span={16}>
                        <Form.Item name="ssex" label="性别：">
                            <Radio.Group>
                                <Radio value="0">男</Radio>
                                <Radio value="1">女</Radio>
                                <Radio value="2">保密</Radio>
                            </Radio.Group>
                        </Form.Item>
                    </Col>
                    <Button onClick={onClose}>取消</Button>
                    <Button onClick={onClose} htmlType="submit" type="primary">保存</Button>
                </Form>
            </Drawer>
        </div>
    )
}
